// 前端监控系统 - 主要功能文件
// 包含按钮创建、配置弹窗、WebSocket连接、定时监控等功能

(function() {
    'use strict';
    
    // 全局变量
    let host = 'https://admin-m2,ddnet66.com/';
    let ws = null;
    let config = {
        interval: 30, // 监听间隔时间（分钟）
        email1001: '13107463918@163.com', // 1001收件邮箱
        email1004: 'chengzi1688cz.com', // 1004收件邮箱地址
        maxAlert: 5000, // 最大预警值
        minAlert: -5000 // 最小预警值
    };
    let monitorTimer = null;
    let heartbeatTimer = null;
    
    // 初始化函数
    function init() {
        loadConfig();
        createButton();
        createConfigPanel();
        connectWebSocket();
        startMonitoring();
    }
    
    // 从localStorage加载配置
    function loadConfig() {
        const savedConfig = localStorage.getItem('monitorConfig');
        if (savedConfig) {
            try {
                config = JSON.parse(savedConfig);
                addLog('配置已从本地存储加载', 'info');
            } catch (e) {
                addLog('配置加载失败，使用默认配置', 'error');
            }
        } else {
            addLog('使用默认配置', 'info');
        }
    }
    
    // 保存配置到localStorage
    function saveConfig() {
        localStorage.setItem('monitorConfig', JSON.stringify(config));
        addLog('配置已保存', 'success');
    }
    
    // 创建固定按钮
    function createButton() {
        const button = document.createElement('button');
        button.innerHTML = '监控配置';
        button.className = 'layui-btn layui-btn-primary';
        button.style.cssText = `
            position: fixed;
            top: 20px;
            right: 20px;
            z-index: 9999;
            background: #1E9FFF;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
        `;
        
        button.addEventListener('click', function() {
            const panel = document.getElementById('monitor-config-panel');
            if (panel) {
                panel.style.display = panel.style.display === 'none' ? 'block' : 'none';
            }
        });
        
        document.body.appendChild(button);
    }
    
    // 创建配置面板
    function createConfigPanel() {
        const panel = document.createElement('div');
        panel.id = 'monitor-config-panel';
        panel.className = 'layui-layer layui-layer-page';
        panel.style.cssText = `
            position: fixed;
            top: 60px;
            right: 20px;
            width: 500px;
            height: 615px;
            background: white;
            border: 1px solid #e6e6e6;
            border-radius: 4px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.15);
            z-index: 10000;
            display: none;
        `;
        
        panel.innerHTML = `
            <div class="layui-layer-title" style="padding: 14px 15px; border-bottom: 1px solid #e6e6e6; background: #f8f8f8; font-size: 14px; font-weight: bold;">
                监控配置
                <span id="close-panel" style="float: right; cursor: pointer; color: #999;">&times;</span>
            </div>
            <div class="layui-layer-content" style="padding: 15px; height: calc(100% - 125px); overflow-y: auto;">
                <!-- 日志区域 -->
                <div class="layui-form-item">
                    <label class="layui-form-label">系统日志:</label>
                    <div class="layui-input-block">
                        <div id="log-area" style="height: 150px; border: 1px solid #e6e6e6; padding: 10px; overflow-y: auto; background: #f9f9f9; font-size: 12px; line-height: 1.5;"></div>
                    </div>
                </div>
                
                <!-- 参数配置 -->
                <div class="layui-form-item">
                    <label class="layui-form-label">监听间隔:</label>
                    <div class="layui-input-block">
                        <input type="number" id="interval" class="layui-input" value="${config.interval}" placeholder="分钟">
                        <div class="layui-form-mid layui-word-aux">分钟</div>
                    </div>
                </div>
                
                <div class="layui-form-item">
                    <label class="layui-form-label">1001收件邮箱:</label>
                    <div class="layui-input-block">
                        <input type="email" id="email1001" class="layui-input" value="${config.email1001}">
                    </div>
                </div>
                
                <div class="layui-form-item">
                    <label class="layui-form-label">1004收件邮箱:</label>
                    <div class="layui-input-block">
                        <input type="email" id="email1004" class="layui-input" value="${config.email1004}">
                    </div>
                </div>
                
                <div class="layui-form-item">
                    <label class="layui-form-label">最大预警值:</label>
                    <div class="layui-input-block">
                        <input type="number" id="maxAlert" class="layui-input" value="${config.maxAlert}">
                    </div>
                </div>
                
                <div class="layui-form-item">
                    <label class="layui-form-label">最小预警值:</label>
                    <div class="layui-input-block">
                        <input type="number" id="minAlert" class="layui-input" value="${config.minAlert}">
                    </div>
                </div>
            </div>
            
            <div class="layui-layer-btn" style="padding: 10px 15px; border-top: 1px solid #e6e6e6; text-align: right;">
                <button id="save-config" class="layui-btn layui-btn-sm">保存配置</button>
            </div>
        `;
        
        // 绑定事件
        panel.querySelector('#close-panel').addEventListener('click', function() {
            panel.style.display = 'none';
        });
        
        panel.querySelector('#save-config').addEventListener('click', function() {
            // 获取表单数据
            config.interval = parseInt(document.getElementById('interval').value) || 30;
            config.email1001 = document.getElementById('email1001').value || '13107463918@163.com';
            config.email1004 = document.getElementById('email1004').value || 'chengzi1688cz.com';
            config.maxAlert = parseInt(document.getElementById('maxAlert').value) || 5000;
            config.minAlert = parseInt(document.getElementById('minAlert').value) || -5000;
            
            saveConfig();
            
            // 重新连接WebSocket并发送新配置
            if (ws && ws.readyState === WebSocket.OPEN) {
                ws.send(JSON.stringify({
                    type: 'config',
                    data: config
                }));
            }
            
            // 重启监控
            startMonitoring();
            
            panel.style.display = 'none';
        });
        
        document.body.appendChild(panel);
    }
    
    // 添加日志
    function addLog(message, type = 'info') {
        const logArea = document.getElementById('log-area');
        if (!logArea) return;
        
        const time = new Date().toLocaleTimeString();
        const colors = {
            success: '#5FB878',
            error: '#FF5722',
            warning: '#FFB800',
            info: '#1E9FFF'
        };
        
        const logEntry = document.createElement('div');
        logEntry.style.color = colors[type] || colors.info;
        logEntry.innerHTML = `[${time}] ${message}`;
        
        logArea.appendChild(logEntry);
        logArea.scrollTop = logArea.scrollHeight;
        
        // 限制日志条数
        const logs = logArea.children;
        if (logs.length > 100) {
            logArea.removeChild(logs[0]);
        }
    }
    
    // 连接WebSocket
    function connectWebSocket() {
        try {
            ws = new WebSocket('ws://localhost:3001');
            
            ws.onopen = function() {
                addLog('WebSocket连接成功', 'success');
                
                // 发送配置信息
                ws.send(JSON.stringify({
                    type: 'config',
                    data: config
                }));
                
                // 开始心跳
                startHeartbeat();
            };
            
            ws.onmessage = function(event) {
                try {
                    const data = JSON.parse(event.data);
                    handleWebSocketMessage(data);
                } catch (e) {
                    addLog('收到无效消息: ' + event.data, 'error');
                }
            };
            
            ws.onclose = function() {
                addLog('WebSocket连接已断开', 'warning');
                stopHeartbeat();
                
                // 5秒后重连
                setTimeout(connectWebSocket, 5000);
            };
            
            ws.onerror = function() {
                addLog('服务未开启，请检查后端服务', 'error');
            };
            
        } catch (e) {
            addLog('WebSocket连接失败: ' + e.message, 'error');
        }
    }
    
    // 处理WebSocket消息
    function handleWebSocketMessage(data) {
        switch (data.type) {
            case 'log':
                addLog(data.message, data.level || 'info');
                break;
            case 'pong':
                // 心跳响应
                break;
            default:
                addLog('收到未知类型消息: ' + data.type, 'warning');
        }
    }
    
    // 开始心跳
    function startHeartbeat() {
        stopHeartbeat();
        heartbeatTimer = setInterval(function() {
            if (ws && ws.readyState === WebSocket.OPEN) {
                ws.send(JSON.stringify({ type: 'ping' }));
            }
        }, 30000); // 30秒心跳
    }
    
    // 停止心跳
    function stopHeartbeat() {
        if (heartbeatTimer) {
            clearInterval(heartbeatTimer);
            heartbeatTimer = null;
        }
    }
    
    // 开始监控
    function startMonitoring() {
        stopMonitoring();
        
        addLog(`开始监控，间隔时间: ${config.interval}分钟`, 'info');
        
        // 立即执行一次
        checkData();
        
        // 设置定时器
        monitorTimer = setInterval(checkData, config.interval * 60 * 1000);
    }
    
    // 停止监控
    function stopMonitoring() {
        if (monitorTimer) {
            clearInterval(monitorTimer);
            monitorTimer = null;
        }
    }
    
    // 检查数据
    async function checkData() {
        try {
            addLog('开始检查数据...', 'info');
            
            // 这里需要替换为实际的API接口
            const response = await fetch(host + 'Compete/Statis/Self');
            
            if (!response.ok) {
                throw new Error(`HTTP ${response.status}: ${response.statusText}`);
            }
            
            const data = await response.json();
            
            // 检查预警值
            const alerts = [];
            
            if (Array.isArray(data)) {
                data.forEach(item => {
                    // 假设数据结构包含 value 和 id 字段
                    if (item.value > config.maxAlert) {
                        alerts.push({
                            ...item,
                            type: '1001', // 超过最大值
                            alertType: 'max',
                            message: `数据 ${item.id} 超过最大预警值: ${item.value} > ${config.maxAlert}`
                        });
                    } else if (item.value < config.minAlert) {
                        alerts.push({
                            ...item,
                            type: '1004', // 低于最小值
                            alertType: 'min',
                            message: `数据 ${item.id} 低于最小预警值: ${item.value} < ${config.minAlert}`
                        });
                    }
                });
            }
            
            if (alerts.length > 0) {
                addLog(`发现 ${alerts.length} 条预警数据`, 'warning');
                
                // 发送预警数据到后端
                alerts.forEach(alert => {
                    addLog(alert.message, 'warning');
                    
                    if (ws && ws.readyState === WebSocket.OPEN) {
                        ws.send(JSON.stringify({
                            type: 'alert',
                            data: alert
                        }));
                    }
                });
            } else {
                addLog('数据检查完成，无预警', 'success');
            }
            
        } catch (error) {
            addLog('数据检查失败: ' + error.message, 'error');
        }
    }
    
    // 页面加载完成后初始化
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        init();
    }
    
    // 页面卸载时清理资源
    window.addEventListener('beforeunload', function() {
        stopMonitoring();
        stopHeartbeat();
        if (ws) {
            ws.close();
        }
    });
    
})();

// 添加基础样式
const style = document.createElement('style');
style.textContent = `
    .layui-form-label {
        width: 150px;
        padding: 9px 15px;
        height: 38px;
        line-height: 20px;
        text-align: right;
        color: #333;
        font-weight: 400;
        float: left;
        box-sizing: border-box;
        flex:none;
    }
    
    .layui-input-block {
        width: calc(100% - 150px);
        // margin-left: 110px;
        // min-height: 36px;
    }
    
    .layui-input {
        display: block;
        width: 100%;
        height: 38px;
        padding: 5px 10px;
        font-size: 14px;
        line-height: 1.3;
        color: #555;
        background-color: #fff;
        background-image: none;
        border: 1px solid #e6e6e6;
        border-radius: 2px;
        box-sizing: border-box;
    }
    
    .layui-btn {
        display: inline-block;
        height: 38px;
        line-height: 38px;
        padding: 0 18px;
        background-color: #1E9FFF;
        color: #fff;
        white-space: nowrap;
        text-align: center;
        font-size: 14px;
        border: none;
        border-radius: 2px;
        cursor: pointer;
        text-decoration: none;
        box-sizing: border-box;
    }
    
    .layui-btn-sm {
        height: 30px;
        line-height: 30px;
        padding: 0 10px;
        font-size: 12px;
    }
    
    .layui-form-item {
        margin-bottom: 15px;
        clear: both;
        display: flex;
        align-items: center;
    }
    
    .layui-form-mid {
        float: left;
        display: block;
        padding: 9px 0;
        line-height: 20px;
        margin-left: 10px;
    }
    
    .layui-word-aux {
        color: #999;
        font-size: 12px;
    }
`;
document.head.appendChild(style);